﻿using ConfExpert.Forms.Base;
using ConfExpert.Forms.Depo;
using ConfExpert.Utility;
using DevExpress.Utils;
using DevTeam;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.SatinAlma
{
    public partial class GPGelenM : XForm
    {
        int CKBatchId;
        double FAO_A, FAO_G;
        public GPGelenM(int _CKBatchId, double _FAO_A, double _FAO_G)
        {
            InitializeComponent();
            CKBatchId = _CKBatchId;
            FAO_A = _FAO_A;
            FAO_G = _FAO_G;

            this.Text += "- " + AppSession.Lookups.CKBatch.FindByCKBatchId(CKBatchId).Notes;
        }

        BindingSource bs1;  //, bs2;
        DataTable dt1, dt2;
        private void GPGelenM_Load(object sender, EventArgs e)
        {
            bs1 = gridView1.Init("GetGPGelenM", CKBatchId, FAO_A, FAO_G, chkALL.Checked);
            gridView1.AddDetailGrid(gridView2, "ProductId");

            dt1 = gridView1.DataTable();
            dt2 = gridView2.DataTable();

            dt1.PrimaryKey = new DataColumn[] { dt1.Columns["ProductId"] };
            dt2.PrimaryKey = new DataColumn[] { dt2.Columns["RollId"] };

            gridView1.AddColumn("QtyMissing", typeof(decimal), "Qty+ISNULL(QtyBUIO,0)-ISNULL(QtyAyrilan,0)");
            gridView1.AddColumn("QtyYeni", typeof(decimal), "SUM(Child({FK}).Qty)");
            gridView2.AddColumn("sel", typeof(bool));
            gridView2.AddColumn("QtySelected", typeof(decimal), "Iif(sel=1, Qty, 0)");
            gridView1.AddColumn("QtySelected", typeof(decimal), "SUM(Child({FK}).QtySelected)");
            gridView1.AddColumn("QtyFark", typeof(decimal), "QtyMissing-QtySelected");

            btnAyir.ItemClick += btnAyir_ItemClick;
            btnSubsetSum.ItemClick += btnSubsetSum_ItemClick;
            btnDeSelect.ItemClick += btnDeSelect_ItemClick;

            gridView1.Columns["OrgProductId"].ColumnEdit = RI(Rp.V_Kumas);
            gridView2.Columns["OrgProductId"].Visible = false;  //TODO: bu kısım MakeColumnInvisible içinde işlenemedi!
            gridView2.MakeColumnInvisible("ProductId", "Scan", "QtySelected", "sel");
            gridView2.AddSummary();
            gridView1.AddSummary("Qty", "QtyBUIO", "QtyAyrilan", "QtyMissing", "QtyYeni", "QtySelected");
            gridView1.FormatAsNumber(1, "Qty", "QtyBUIO", "QtyAyrilan", "QtyMissing", "QtyYeni", "QtySelected", "QtyFark");
            gridView1.RowCellStyle += new DevExpress.XtraGrid.Views.Grid.RowCellStyleEventHandler(gridView1_RowCellStyle);
            splitContainerControl1.AutoSize();
            gridView1.MakeReadOnly();
            gridView2.MakeReadOnly();

            Rfrsh();

            GridManager gm = GridManager.GetManager(gridView1);
            gm.GridMenu.AddMenu("Seç", Sec1);
            gm.GridMenu.AddMenu("Bırak", Birak1);

            GridManager gm2 = GridManager.GetManager(gridView2);
            gm2.GridMenu.AddMenu("Seç", Sec2);
            gm2.GridMenu.AddMenu("Bırak", Birak2);

            gridView1.OptionsView.EnableAppearanceEvenRow =
            gridView2.OptionsView.EnableAppearanceEvenRow =
            gridView1.OptionsView.EnableAppearanceOddRow =
            gridView2.OptionsView.EnableAppearanceOddRow =
            false;

            gridView1.RowStyle += new DevExpress.XtraGrid.Views.Grid.RowStyleEventHandler(gridView1_RowStyle);
            gridView2.RowStyle += new DevExpress.XtraGrid.Views.Grid.RowStyleEventHandler(gridView2_RowStyle);

            chkALL.CheckedChanged += chkALL_CheckedChanged;

            gridView1.FocusedRowChanged += gridView1_FocusedRowChanged;
        }

        void chkALL_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Rfrsh();
        }

        void btnDeSelect_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            foreach (DataRow dr in dt2.Select(""))
                dr["sel"] = false;
        }

        void btnSubsetSum_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gridView1.EndEditing();
            gridView2.EndEditing();
            int[] selectedRowIds = gridView1.GetSelectedRows();
            List<int> selectedRollIds = new List<int>();

            foreach (int rowIndex in selectedRowIds)
            {
                int productId = (int)gridView1.GetDataRow(rowIndex)["ProductId"];
                decimal target = dt1.Rows.Find(productId)["QtyMissing"].ToDecimal();

                DataRow[] drLines = dt2.Select("ProductId =" + productId);

                Dictionary<int, decimal> rolls = new Dictionary<int, decimal>();
                foreach (DataRow dr in drLines)
                {
                    int rollID = (int)dr["RollId"];
                    decimal qty = Convert.ToDecimal(dr["Qty"]);
                    rolls.Add(rollID, qty);
                }

                List<int> selectedRollId = SubsetSum.Select(target, rolls);
                selectedRollIds.AddRange(selectedRollId);
            }

            string strRollIds = string.Join(", ", Array.ConvertAll(selectedRollIds.ToArray(), i => i.ToString()));

            DataRow[] drSelectedRows = dt2.Select("RollId in (" + strRollIds + ")");
            foreach (DataRow dr in drSelectedRows)
                dr["sel"] = true;

            //Clipboard.SetText(strRollIds);
            ClipboardPaste(strRollIds);
        }

        void btnAyir_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            string str = string.Empty;
            DataTable se = new DataTable();
            DataTable sel = new DataTable();

            se.Columns.Add("ProductId", typeof(int));
            se.Columns.Add("MuadilTipId", typeof(int));
            se.Columns.Add("AlternatifId", typeof(int));

            sel.Columns.Add("RollId", typeof(int));
            sel.Columns.Add("ProductId", typeof(int));
            sel.Columns.Add("QtySelected", typeof(decimal));

            foreach (DataRow glr in dt2.Rows)
                if (glr["sel"] != null)
                    if (glr["sel"] != DBNull.Value)
                        if (boolParse(glr["sel"]))
                        {
                            DataRow slr = sel.NewRow();
                            slr["RollId"] = glr["RollId"];
                            slr["QtySelected"] = glr["Qty"];
                            slr["ProductId"] = glr["ProductId"];
                            sel.Rows.Add(slr);
                            str += glr["RollId"].ToString() + ","; //+ Environment.NewLine;
                        }

            foreach (DataRow gr in dt1.Rows)
            {
                DataRow sr = se.NewRow();
                sr["AlternatifId"] = gr["OrgProductId"];
                sr["MuadilTipId"] = 1;    //Kalıcı
                sr["ProductId"] = gr["ProductId"];
                se.Rows.Add(sr);
            }

            if (sel.Rows.Count > 0)
            {
                bool yetkili = isAdmin || ytk(73); //Meyzi+Gamze
                using (Transfer t = new Transfer(sel, se, yetkili, CKBatchId))
                {
                    if (t.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        Rfrsh();
                }
            }
        }

        void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            gridView2.BestFitColumns();
        }


        void gridView1_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            //e.Appearance.BackColor = ((GridView)sender).GetRowCellDisplayText(e.RowHandle, "QtySelected").ToStr() != string.Empty ? Color.LightBlue : Color.White;

            if (e.RowHandle > -1)
            {
                if (gridView1.GetRowCellValue(e.RowHandle, "QtySelected").ToDecimal() > 0)
                    e.Appearance.BackColor = e.Appearance.BackColor2 = Color.LightBlue;   // Color.FromArgb(255, 192, 0);
                else
                    e.Appearance.Combine((e.RowHandle & 1) != 0 ? gridView1.Appearance.EvenRow : gridView1.Appearance.OddRow);
            }
        }

        void gridView2_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            //e.Appearance.BackColor = boolParse(((GridView)sender).GetRowCellValue(e.RowHandle, "sel")) ? Color.LightBlue : Color.White;

            if (e.RowHandle > -1)
            {
                if (boolParse(gridView2.GetRowCellValue(e.RowHandle, "sel")))
                    e.Appearance.BackColor = e.Appearance.BackColor2 = Color.LightBlue;   // Color.FromArgb(255, 192, 0);
                else
                    e.Appearance.Combine((e.RowHandle & 1) != 0 ? gridView2.Appearance.EvenRow : gridView2.Appearance.OddRow);
            }
        }


        void Sec1(object sender, EventArgs e)
        {
            foreach (int handle in gridView1.GetSelectedRows())
            {
                int ProductId = intParse(gridView1.GetRowCellValue(handle, "ProductId"));
                foreach (DataRow r in dt2.Select("ProductId = " + ProductId.ToString()))
                    r["sel"] = 1;
            }
        }


        void Birak1(object sender, EventArgs e)
        {
            foreach (int handle in gridView1.GetSelectedRows())
            {
                int ProductId = intParse(gridView1.GetRowCellValue(handle, "ProductId"));
                foreach (DataRow r in dt2.Select("ProductId = " + ProductId.ToString()))
                    r["sel"] = 0;
            }
        }

        void Sec2(object sender, EventArgs e)
        {
            foreach (int handle in gridView2.GetSelectedRows())
            {
                int RollId = intParse(gridView2.GetRowCellValue(handle, "RollId"));
                dt2.Rows.Find(RollId)["sel"] = 1;
            }
        }


        void Birak2(object sender, EventArgs e)
        {
            foreach (int handle in gridView2.GetSelectedRows())
            {
                int RollId = intParse(gridView2.GetRowCellValue(handle, "RollId"));
                dt2.Rows.Find(RollId)["sel"] = 0;
            }
        }

        private void Rfrsh()
        {
            gridView1.RefreshDataSource("GetGPGelenM", CKBatchId, FAO_A, FAO_G, chkALL.Checked);
            bs1.Filter = "QtyMissing>0 and QtyYeni>0";
            gridView1.UpdateTotalSummary();
            gridView1.BestFitColumns();
            gridView2.BestFitColumns();
        }

        void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            if (e.Column.FieldName == "QtyYeni" ||
                e.Column.FieldName == "OrgProductId")
                e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
        }



        // This allows the clipboard to have something copied to it.
        public static void ClipboardPaste(String pasteString)
        {
            // This clears the clipboard
            Clipboard.Clear();

            // This is a "Try" of the statement inside {}, if it fails it goes to "Catch"
            // If it "Catches" an exception. Then the function will retry itself.
            try
            {
                // This, per some suggestions I found is a half second second wait before another
                // clipboard clear and before setting the clipboard
                System.Threading.Thread.Sleep(500);
                Clipboard.Clear();
                // This is, instead of using SetText another method to put something into
                // the clipboard, it includes a retry/fail set up with a delay
                // It retries 5 times with 250 milliseconds (0.25 second) between each retry.
                Clipboard.SetDataObject(pasteString, false, 5, 250);
            }
            catch (Exception)
            {
                ClipboardPaste(pasteString);
            }
        }



    }
}
